package com.zhenhe.api.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.zhenhe.api.exception.ApiAuthenticationException;
import com.zhenhe.api.exception.ApiException;
import com.zhenhe.api.login.APILoginUtil;
import com.zhenhe.core.common.utils.StringUtils;
import com.zhenhe.core.common.utils.http.IPUtil;
import com.zhenhe.core.dto.APIResultDto;
import com.zhenhe.core.entity.TUserEntity;
import com.zhenhe.core.modules.service.LoginService;
import com.zhenhe.core.modules.service.TUserService;

public class APICommonInterceptor extends HandlerInterceptorAdapter{

	private static final Logger log = LoggerFactory.getLogger(APICommonInterceptor.class);
	
	@Value("${apiPassUrl}")
	private String apiPassUrl;
	
	private static final String apiToken="token";
	
	@Value("${api.debug}")
	private String debug;
	
	private static final String TOKEN = "";
	
	@Resource
	private TUserService tuserService;
	
	@Resource
	private LoginService loginService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "application/json;charset=UTF-8");
		
		log.debug("api请求url:{},ip:{}", request.getRequestURI(),IPUtil.getIp(request));
		
//		if(!loginService.inLoginTime()){
//			String errStr = APILoginUtil.systemErrorJsonString();
//			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//			response.getWriter().write(errStr);
//			response.getWriter().flush();
//			response.getWriter().close();
//			return false;
//		}
		
//		if(StringUtils.isNotBlank(apiPassUrl)){
//			String[] passUrl=apiPassUrl.split(",");
//			for(String p:passUrl){
//				if(request.getRequestURL().toString().contains(p))
//					return true;
//			}
//		}
//		
//		String apiToken = request.getParameter(APICommonInterceptor.apiToken);
//		if(apiToken==null&&Boolean.valueOf(debug)){
//			apiToken = TOKEN;
//		}
//		if(StringUtils.isBlank(apiToken)){
//			log.debug("api用户未登录");
//			response.getWriter().write(APILoginUtil.unAuthorityJsonString());
//			return false;
//		}
//		
//		TUserEntity member;
//		try{
//			member = tuserService.getMemberToken(apiToken);
//		}catch(ApiAuthenticationException e){
//			log.debug("api用户未登录或登陆超时");
//			response.getWriter().write(e.getMessage());
//			return false;
//		}
//		APILoginUtil.putLogintuser(member);
//		MDC.put("user", member.getUserAccount());
		return true;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if(ex!=null){
			if(ex instanceof ApiException){
				ApiException apiEx = (ApiException) ex;
				APIResultDto dto = apiEx.getError();
				if(dto!= null){
					log.info("业务处理失败:{}",dto);
					response.getWriter().write(JSONObject.toJSONString(dto));
					response.getWriter().flush();
					response.getWriter().close();
					return ;
				}
			}
			log.error("API接口异常", ex);
			String errStr = APILoginUtil.systemErrorJsonString();
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.getWriter().write(errStr);
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
	}
	
}